# encoding:utf-8

from baseHandler import BaseRequestHandler
# 这个并发库在python3自带;在python2需要安装sudo pip install futures
from model.user import User
from model.pool import Pool
from sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound
from tornado.gen import coroutine
from middleware.authMiddleware import PermissionCheckMiddleware

try:
    import json
except ImportError:
    import simplejson as json


class UserHandler(BaseRequestHandler):
    middleware = (PermissionCheckMiddleware(),)

    @coroutine
    def get(self):
        def _lambda(db):
            users = db.query(User).all()
            response_list = []
            for user in users:
                response_list.append(user.to_dict())
            return response_list

        response_list = yield self.asyncdb(_lambda)
        self.write({'status': 'OK', 'output': response_list})

    @coroutine
    def post(self):
        ak = self.get_argument('ak')
        sk = self.get_argument('sk')
        permission = self.get_argument('permission')
        is_superuser = self.get_argument('superuser', False)
        pools = self.get_argument('pools')

        def _lambda(db):
            try:
                user = db.query(User).filter_by(access_key=ak).one()
            except NoResultFound:
                user = User(ak, sk, permission, is_superuser)
                db.add(user)
                db.commit()
            except MultipleResultsFound:
                users = db.query(User).filter_by(access_key=ak).all()
                users_len = len(users)
                num = 0
                for u in users:
                    if num < users_len:
                        db.delete(u)
                        db.commit()
                        num +=1
                    else:
                        user = u
            db_pools = [pool.name for pool in db.query(Pool).all()]
            for pool in pools.split(','):
                if pool not in db_pools:
                    p = Pool(pool)
                    db.add(p)
                    db.commit()
                else:
                    p = db.query(Pool).filter_by(name=pool).one()

                user.pools.append(p)
            db.commit()

        yield self.asyncdb(_lambda)

        self.write({'status': 'OK', 'output': ''})

    @coroutine
    def delete(self):
        key = self.get_argument('ak')

        def _lambda(db):
            try:
                user = db.query(User).filter_by(access_key=key).one()
                db.delete(user)
                db.commit()
            except NoResultFound:
                pass

        yield self.asyncdb(_lambda)

        self.write({'status': 'OK', 'output': ''})


class UserPoolHandler(BaseRequestHandler):
    middleware = (PermissionCheckMiddleware(),)

    def get(self):
        try:
            ak = self.get_argument('key')
            user = self.db.query(User).filter_by(access_key=ak).one()
            pools = user.pools.split(',')
            self.write({'status': 'OK', 'output': pools})
        except NoResultFound:
            self.write({'status': 'ERROR', 'output': 'Not find  key'})

    def post(self):
        try:
            ak = self.get_argument('key')
            pools = self.get_argument('pools')
            user = self.db.query(User).filter_by(access_key=ak).one()
            user.add_pools(pools)
            self.db.add(user)
            self.db.commit()
            self.write({'status': 'OK', 'output': 'update pool output OK'})
        except NoResultFound:
            self.write({'status': 'ERROR', 'output': 'Not find  key'})

    def delete(self):
        try:
            ak = self.get_argument('key')
            pools = self.get_argument('pools')
            user = self.db.query(User).filter_by(access_key=ak).one()
            user.del_pools(pools)
            self.write({'status': 'OK', 'output': 'update pool output OK'})
        except NoResultFound:
            self.write({'status': 'ERROR', 'output': 'Not find  key'})
